package com.gitee.wsl.common.chart

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.gitee.wsl.common.draw.gesture.ChartTouch
import com.gitee.wsl.common.chart.sample.XChart
import com.gitee.wsl.common.ui.api.InvalidateAble

import timber.log.Timber

open class ChartView : View {

    private val touchList = mutableListOf<ChartTouch>()
    private val chartList = mutableListOf<XChart>()

    constructor(context: Context) : super(context) {
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int):super(context, attrs, defStyle) {
    }

    init {
        initChartView()
    }

    protected fun initChartView() {
        //禁用硬件加速
        //disableHardwareAccelerated()
    }

    /**
     * 刷新图表
     */
    fun refreshChart() {
        this.invalidate()
    }

    /**
     * 绘制图表
     * @param canvas    画布
     */
     open fun render(canvas: Canvas){
        chartList.forEach {
            it.render(canvas)
        }
     }

    override fun onDraw(canvas: Canvas) {
        try {
            render(canvas)
        } catch (e: Exception) {
           Timber.d( e.toString())
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        chartList.forEach {
            //图所占范围大小
            it.setChartRange(w.toFloat(), h.toFloat())
            /*it.chartCommutator.setContentRect(
                getWidth().toFloat(), getHeight().toFloat(), paddingLeft.toFloat(), paddingTop.toFloat(), paddingRight.toFloat(),
                paddingBottom.toFloat()
            )*/
        }
    }

    override fun computeScroll() {
        super.computeScroll()
        chartList.forEach {
            it.computeScroll()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            measureWidth(widthMeasureSpec),
            measureHeight(heightMeasureSpec)
        )
    }

    private fun measureWidth(measureSpec: Int): Int {
        var result = 100
        val specMode = MeasureSpec.getMode(measureSpec)
        val specSize = MeasureSpec.getSize(measureSpec)
        if (specMode == MeasureSpec.EXACTLY) { //fill_parent
            result = specSize
        } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content
            result = result.coerceAtMost(specSize)
        }
        return result
    }

    private fun measureHeight(measureSpec: Int): Int {
        var result = 100
        val specMode = MeasureSpec.getMode(measureSpec)
        val specSize = MeasureSpec.getSize(measureSpec)
        if (specMode == MeasureSpec.EXACTLY) { //fill_parent
            result = specSize
        } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content
            result = result.coerceAtMost(specSize)
        }
        return result
    }

    /**
     * 禁用硬件加速.
     * 原因:android自3.0引入了硬件加速，即使用GPU进行绘图,但它并不能完善的支持所有的绘图，
     * 通常表现为内容(如Rect或Path)不可见，异常或渲染错误。所以类了保证图表的正常显示，强制禁用掉.
     */
    protected fun disableHardwareAccelerated() {
        //View.isHardwareAccelerated()
        //Canvas.isHardwareAccelerated()
       //是否开启了硬件加速,如开启将其禁掉
       if (!isHardwareAccelerated) {
                //setLayerType(View.LAYER_TYPE_NONE,null);  //LAYER_TYPE_SOFTWARE
            setLayerType(LAYER_TYPE_SOFTWARE, null)
       }
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // TODO Auto-generated method stub
        //touchChart(event);
        touchEvent(event)

        return true
    }


    //////////////////////////////////////////////////////
    //用于手势操作来平移或放大缩小图表
    //////////////////////////////////////////////////////
    /**
     * 用于绑定需要手势滑动的图表
     * @param view  视图
     * @param chart 图表类
     */
    open fun bindTouch(view: View, chart: XChart) {
        chart.init(context)
        chart.invalidateCallBack= com.gitee.wsl.common.ui.api.InvalidateAble {
            postInvalidate()
        }
        //touchList.add(ChartTouchImp(this, chart))
        /*val handler=ChartTouchHandler(context,chart)
        touchList.add(handler)*/
        chartList.add(chart)
    }

    /**
     * 用于绑定需要手势滑动的图表，及指定可滑动范围
     * @param view  视图
     * @param chart    图表类
     * @param panRatio 需大于0
     */
    open fun bindTouch(view: View, chart: XChart, panRatio: Float) {
        chart.init(context)
        chart.invalidateCallBack= com.gitee.wsl.common.ui.api.InvalidateAble {
            invalidate()
        }
        //touchList.add(ChartTouchImp(this, chart, panRatio))
       /* val handler=ChartTouchHandler(context,chart)
        touchList.add(handler)*/
        chartList.add(chart)
    }

    /**
     * 清空绑定类
     */
    open fun restTouchBind() {
        touchList.clear()
    }

    /**
     * 触发手势操作
     * @param event
     * @return
     */
    private fun touchEvent(event: MotionEvent): Boolean {
        chartList.forEach {
            if(it.handleTouch(event))
                invalidate()
        }
        return true
    }
}